var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var webim = global.webim;
var webimhandler = global.webimhandler;
var employee = {};
var userSignInfo;
var changeTime = require("../../../utils/changetime.js");
var h = require("../../../data_file/data_dispose");
var em = require("../../../data_file/emtion")
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    contactList:[],
    hasLoad:false,
    selectedCount:0,
    relationMap: {},
    searchUserName:"",
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var that = this;
    userSignInfo = wx.getStorageSync("IMUserSignInfo");
    that.setData({
      emtions: em.changeEm()
    })
    webimhandler.setNewMsgListener(function (newmsg) {
      that.loadRecentContactList(options);
    });
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      employee = wx.getStorageSync("employee");
      that.loadRecentContactList(options);
      that.findGroupList();
    });
  },

  recountSelected(){
    let that = this;
    let count = 0;
    let contactList = that.data.contactList;
    let customerByGroup = that.data.customerByGroup;
    app.globalData.groupSendList = [];
    contactList.forEach((item,index)=>{
      if (item.isSelected){
        that.addItemToGroupsendList(item);
      }
    })
    for (let i in that.data.customerByGroup){
      let customList = that.data.customerByGroup[i];
      customList.forEach((item, index) => {
        if (item.isSelected) {
          that.addItemToGroupsendList(item);
        }
      })
    }
    that.setData({
      selectedCount: app.globalData.groupSendList.length
    })
  },

  // 去重添加
  addItemToGroupsendList(user){
    if (!app.globalData.groupSendList){
      app.globalData.groupSendList = [];
    }
    let groupSendList = app.globalData.groupSendList;
    let flag = false;
    groupSendList.forEach(function(item,index){
      if(item.id == user.id){
        flag = true;
      }
    });
    if (!flag){
      groupSendList.push(user);
    }
  },

  findGroupList() {
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/relationgroup/findList",
      data: {
        cusmallToken: cusmallToken,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          let list = data.model.list;
          let customerByGroup = {};
          for (let item of list) {
            customerByGroup[item.id] = [];
            item.expand = false;
          }
          ctx.setData({
            groupList: data.model.list,
            customerByGroup: customerByGroup
          });
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({ isLoading: false });
      }
    });
  },

  loadRecentContactList: function (options){
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/findByEmployeeOpenId",
      data: {
        cusmallToken: cusmallToken,
        start: 0,
        limit: 100
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        wx.hideLoading();
        if (data && 0 === data.ret) {
          if (data.model.relation) {
            for (let item of data.model.relation) {
              that.setData({
                ['relationMap.' + item.memberId + '']: item

              });
            }
          } else {
            that.setData({
              relationMap: null
            })
          }
          that.setData({
            contactList: data.model.list,
            total: data.model.total
          });
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        that.setData({ isLoading: false });
      }
    });
  },

  searchUser(){
    var that = this;
    var contactList = that.data.contactList;

    if (contactList && contactList.length > 0){
      contactList.forEach(function(item){
        if (that.data.searchUserName && item.nickName.indexOf(that.data.searchUserName) == -1){
          item.isHidden = true;
        } else {
          item.isHidden = false;
        }
      });
    }
    
    that.setData({
      contactList: contactList
    })
  },

  changeInput(e) {
    this.setData({
      searchUserName: e.detail.value
    });
    //this.searchUser();
  },

  clearInput() {
    this.setData({
      searchUserName: ""
    });
    this.searchUser();
  },

  getAllUnreadNum:function(cb){
    var that = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/chatmsg/getAllUnreadNum",
      data: {
        cusmallToken: cusmallToken,
        openid: employee.openid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        cb && cb(res.data.model.list);
      },
      fail() {

      },
      complete() {
      }
    });
  },

  changeSelect:function(e){
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var item = that.data.contactList[idx];
    item.isSelected = !item.isSelected;
    that.setData({
      ["contactList[" + idx + "]"]: item
    })
    that.recountSelected();
  },
  changeSelectInGroup:function(e){
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var selectedGroup = that.data.selectedGroup;
    var item = that.data.customerByGroup[selectedGroup.id][idx];
    item.isSelected = !item.isSelected;
    that.setData({
      ["customerByGroup." + selectedGroup.id + "["+idx+"]"]: item
    })
    that.recountSelected();
  },
  changeGroupSelect:function(e){
    var that = this;
    var idx = e.currentTarget.dataset.idx;
    var item = that.data.groupList[idx];
    item.isSelected = !item.isSelected;
    if (item.isSelected){
      if (0 < that.data.customerByGroup[item.id].length) {
        var customerList = that.data.customerByGroup[item.id];
        customerList.forEach(function(item,index){
          item.isSelected = true;
        });
        that.setData({
          ["customerByGroup." + item.id + ""]: customerList
        })
        
      } else {
        wx.request({
          url: cf.config.pageDomain + "/applet/mobile/visitcard/relationgroup/findGroupMemberList",
          data: {
            cusmallToken: cusmallToken,
            groupId: item.id
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            var data = res.data;
            if (data && 0 === data.ret) {
              var list = data.model.list || [];
              list.forEach(function (item, index) {
                item.isSelected = true;
              });
              that.setData({
                ["customerByGroup." + item.id + ""]: list
              });
              that.recountSelected();
            } else {
              wx.showToast({
                title: data.msg,
                icon: "none"
              });
            }
          },
          fail() {

          },
          complete() {
            that.setData({
              loadingCus: false
            });
          }
        });
      }
    } else {
      if (0 < that.data.customerByGroup[item.id].length) {
        var customerList = that.data.customerByGroup[item.id];
        customerList.forEach(function (item, index) {
          item.isSelected = false;
        });
        that.setData({
          ["customerByGroup." + item.id + ""]: customerList
        })

      }
    }
    that.setData({
      ["groupList[" + idx + "]"]: item
    })
    that.recountSelected();
  },
  groupSend:function(){
    let that = this;
    let contactList = that.data.contactList;
    for(let i=0;i<contactList.length;i++){
      let customer = contactList[i];
      webimhandler.init({
        accountMode: 0
        , pageCtx: that
        , accountType: userSignInfo.imAccountType
        , identifier: userSignInfo.identifier
        , userSig: userSignInfo.sign
        , sdkAppID: userSignInfo.imAppId
        , selType: webim.SESSION_TYPE.C2C
        , selToID: customer.To_Account
        , selSess: null //当前聊天会话
      });
      var postObj = {
        type: 2,
        head_img: customer.MsgShow.to_userinfo.headUrl,
        from_userinfo: userSignInfo,
        to_userinfo: customer.MsgShow.to_userinfo, 
        card_id: customer.MsgShow.card_id,
        msg: {
          type: 0,
          context: "测试群发消息2",
          from: customer.MsgShow.to_userinfo.nickName
        }
      };
      webimhandler.onSendMsg(JSON.stringify(postObj), function (t) {
       
      }, function () {
      
      });
    }
  },

  gotoNext:function(){
    var that = this;
    if (that.data.selectedCount == 0){
      wx.showToast({
        title: '请选择用户',
        icon: 'none'
      })
      return;
    }
    if (that.data.selectedCount > 30){
      wx.showToast({
        title: '最多可以选择30个客户',
        icon: 'none'
      })
      return;
    }
    wx.navigateTo({
      url: '../chat/chat?isGroupSend=true',
    })
  },
  backToHome(){
    var ctx = this;
    ctx.setData({
      selectedGroupId: "",
      selectedGroup: null
    });
  },
  getGroupCustomer(e) {
    var ctx = this;
    let groupId = e.currentTarget.dataset.gid;
    let idx = e.currentTarget.dataset.idx;
    ctx.setData({
      selectedGroupId: groupId,
      selectedGroupIdx: idx,
      selectedGroup: ctx.data.groupList[idx]
    });
    if (0 < ctx.data.customerByGroup[groupId].length || ctx.data.loadingCus) {
      return;
    }
    ctx.setData({
      loadingCus: true
    });
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/relationgroup/findGroupMemberList",
      data: {
        cusmallToken: cusmallToken,
        groupId: groupId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        wx.hideLoading();
        if (data && 0 === data.ret) {
          var list = data.model.list || [];
          ctx.setData({
            ["customerByGroup." + groupId + ""]: list
          });

        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          });
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({
          loadingCus: false
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {

  }
}))